<template>
    <view class="container">
        <view v-if="!ids || type">
            <view class="flex_wrap row_between row_middle">
                <view @click="look">预览</view>
                <view class="right" @click="publish">发表</view>
            </view>
            <view>
                <view class="content" v-if="!myStyle">
                    <u-textarea
                        v-model="videoIntro"
                        :maxlength="1000"
                        placeholder="请输入您要发表的标题~"
                        autoHeight
                        :customStyle="{
                            backgroundColor: '#fff',
                            color: '#333',
                            fontSize: '28rpx',
                            border: 'none',
                            height: '140rpx',
                        }"
                    ></u-textarea>
                </view>
                <view
                    class="content huaTiBox"
                    style="padding-bottom: 16rpx"
                    v-if="!myStyle"
                >
                    <u-textarea
                        v-model="huaTi"
                        :maxlength="1000"
                        placeholder="请输入您要发表的话题~"
                        autoHeight
                        :customStyle="{
                            backgroundColor: '#fff',
                            fontSize: '28rpx',
                            border: 'none',
                            minHeight: '140rpx',
                        }"
                    ></u-textarea>
                    <view class="talkBox" @click="addTalkBtn"># 话题</view>
                </view>
                <view class="content">
                    <u-textarea
                        v-model="value"
                        :maxlength="1000000"
                        placeholder="请输入您要发表的第一段内容~"
                        autoHeight
                        :customStyle="{
                            backgroundColor: '#fff',
                            color: '#333',
                            fontSize: '28rpx',
                            border: 'none',
                        }"
                    ></u-textarea>
                    <u-upload
                        :fileList="fileList"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        :previewFullImage="true"
                        name="0"
                        multiple
                        :maxCount="3"
                        width="200rpx"
                        height="200rpx"
                        accept="image"
                        uploadIcon="plus"
                        :customStyle="{
                            marginLeft: '20rpx',
                            marginTop: '40rpx',
                        }"
                    ></u-upload>
                </view>
                <view class="content">
                    <u-textarea
                        v-model="value1"
                        ref="textarea"
                        placeholder="请输入您要发表的第二段内容~"
                        autoHeight
                        :customStyle="{
                            backgroundColor: '#fff',
                            color: '#333',
                            fontSize: '28rpx',
                            border: 'none',
                        }"
                    ></u-textarea>
                    <u-upload
                        :fileList="fileList1"
                        @afterRead="afterRead1"
                        @delete="deletePic1"
                        :previewFullImage="true"
                        uploadIcon="plus"
                        name="1"
                        multiple
                        :maxCount="3"
                        width="200rpx"
                        height="200rpx"
                        accept="image"
                        :customStyle="{
                            marginLeft: '20rpx',
                            marginTop: '40rpx',
                        }"
                    ></u-upload>
                </view>
                <view class="content">
                    <u-textarea
                        v-model="value2"
                        ref="textarea"
                        placeholder="请输入您要发表的第三段内容~"
                        autoHeight
                        :customStyle="{
                            backgroundColor: '#fff',
                            color: '#333',
                            fontSize: '28rpx',
                            border: 'none',
                        }"
                    ></u-textarea>
                    <u-upload
                        :fileList="fileList2"
                        @afterRead="afterRead2"
                        @delete="deletePic2"
                        :previewFullImage="true"
                        name="2"
                        multiple
                        :maxCount="3"
                        width="200rpx"
                        height="200rpx"
                        accept="image"
                        uploadIcon="plus"
                        :customStyle="{
                            marginLeft: '20rpx',
                            marginTop: '40rpx',
                        }"
                    ></u-upload>
                </view>
            </view>
        </view>
        <view class="wrap" v-if="ids && !type">
            <view v-if="!myStyle">
                <view
                    style="font-weight: 400; font-size: 40rpx; color: #161616"
                    >{{ videoIntro }}</view
                >
                <view
                    class="flex_wrap"
                    style="flex-wrap: wrap"
                    v-if="tag.length"
                >
                    <text
                        style="
                            padding: 0 10rpx 0 0;
                            font-weight: 400;
                            font-size: 32rpx;
                            color: #588bf3;
                        "
                        v-for="v in tag"
                        @click="openList(v)"
                        >#{{ v }}</text
                    ></view
                ></view
            >
            <view
                class="album__content"
                v-for="item in dataList"
                :key="item.id"
            >
                <u-text
                    :customStyle="{
                        whiteSpace: 'pre-wrap',
                        wordBreak: 'break-word',
                    }"
                    margin="16px 0"
                    :text="item.text"
                    :key="item.id"
                ></u-text>
                <image
                    v-for="(e, i) in item.img"
                    :src="e.url || e"
                    mode="widthFix"
                    :key="i"
                ></image>
            </view>
        </view>
        <u-popup
            closeable
            :show="show"
            @close="show = false"
            @open="show = true"
            safeAreaInsetTop
            :closeOnClickOverlay="false"
            :overlayStyle="{ 'touch-action': 'none' }"
            :customStyle="{
                height: '100vh',
                flex: 'none',
            }"
        >
            <view class="wrap" style="padding-left: 50rpx">
                <view v-if="!myStyle">
                    <view
                        style="
                            font-weight: 400;
                            font-size: 40rpx;
                            color: #161616;
                        "
                        >{{ videoIntro }}</view
                    >
                    <view
                        v-if="huaTi"
                        style="
                            margin: 16rpx 0;
                            font-weight: 400;
                            font-size: 32rpx;
                            color: #588bf3;
                        "
                        >{{ huaTi[0] === "#" ? huaTi : `#${huaTi}` }}</view
                    ></view
                >
                <view
                    class="album__content"
                    v-for="item in dataList"
                    :key="item.id"
                >
                    <u-text
                        :customStyle="{
                            whiteSpace: 'pre-wrap',
                            wordBreak: 'break-word',
                        }"
                        margin="16px 0"
                        :text="item.text"
                        :key="item.id"
                    ></u-text>
                    <image
                        v-for="(e, i) in item.img"
                        :src="e.url"
                        mode="widthFix"
                        :key="i"
                    ></image>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig.js";
import {
    uploadBlog,
    getBlogInfo,
    editBlog,
} from "@/api/consultationSalesman.js";
import {
    editBlogCustomer,
    uploadBlogCustomer,
    getBlogInfoCustomer,
} from "@/api/customerAgent.js";
import { mapGetters } from "vuex";
import {
    updateCustomerByCustomerId,
    getCustomerByIdNoToken,
} from "@/api/login.js";
export default {
    data() {
        return {
            value: "",
            value1: "",
            value2: "",
            fileList: [],
            fileList1: [],
            fileList2: [],
            show: false,
            dataList: [],
            customerId: "",
            ids: "",
            type: "",
            myStyle: "",
            videoIntro: "",
            huaTi: "",
            tag: [],
            releaseManId: "",
            currentTab: "",
        };
    },
    computed: {
        ...mapGetters(["userInfo"]),
    },

    onLoad(options) {
        if (options.myStyle) {
            this.myStyle = options.myStyle;
            this.customerId = options.customerId;
            uni.setNavigationBarTitle({
                title: "个人风采",
            });
            if (options.edit) {
                getCustomerByIdNoToken(this.customerId).then((res) => {
                    if (res.code == 200) {
                        const myStyle = res.data?.myStyle ?? [];
                        const list = JSON.parse(myStyle);
                        console.log("myStyle", list);
                        this.dataList = list;
                        // 编辑
                        if (options.type == 1) {
                            this.type = options.type;
                            this.value = list[0]?.text ?? "";
                            this.fileList = list[0]?.img
                                ? list[0]?.img.map((v) => ({ url: v.url || v }))
                                : [];
                            this.value1 = list[1]?.text ?? "";
                            this.fileList1 = list[1]?.img
                                ? list[1]?.img.map((v) => ({ url: v.url || v }))
                                : [];
                            this.value2 = list[2]?.text ?? "";
                            this.fileList2 = list[2]?.img
                                ? list[2]?.img.map((v) => ({ url: v.url || v }))
                                : [];
                        }
                    }
                });
            }
        }
        // 编辑
        if (options.id) {
            this.ids = decodeURIComponent(options.id);
            if (this.$store.getters?.authority === "customer") {
                getBlogInfoCustomer(this.ids).then((res) => {
                    this.videoIntro = res.data?.videoIntro;
                    this.huaTi =
                        res.data?.tag && res.data?.tag.replace(/,/g, "#");
                    if (res.data.tag) {
                        this.tag = res.data.tag
                            .split(",")
                            .filter((ele) => ele && ele !== " ");
                        console.log("tag :>> ", this.tag);
                    }

                    const list = JSON.parse(res.data.infoDetail);
                    if (res.code === 200) this.dataList = list;
                    // 编辑
                    if (options.type == 1) {
                        this.type = options.type;
                        this.value = list[0]?.text ?? "";
                        this.fileList = list[0]?.img
                            ? list[0]?.img.map((v) => ({ url: v.url || v }))
                            : [];
                        this.value1 = list[1]?.text ?? "";
                        this.fileList1 = list[1]?.img
                            ? list[1]?.img.map((v) => ({ url: v.url || v }))
                            : [];
                        this.value2 = list[2]?.text ?? "";
                        this.fileList2 = list[2]?.img
                            ? list[2]?.img.map((v) => ({ url: v.url || v }))
                            : [];
                    }
                });
            } else {
                getBlogInfo(this.ids).then((res) => {
                    this.videoIntro = res.data?.videoIntro;
                    this.huaTi =
                        res.data?.tag && res.data?.tag.replace(/,/g, "#");
                    if (res.data.tag) {
                        this.tag = res.data.tag
                            .split(",")
                            .filter((ele) => ele && ele !== " ");
                        console.log("tag :>> ", this.tag);
                    }

                    const list = JSON.parse(res.data.infoDetail);
                    if (res.code === 200) this.dataList = list;
                    // 编辑
                    if (options.type == 1) {
                        this.type = options.type;
                        this.value = list[0]?.text ?? "";
                        this.fileList = list[0]?.img
                            ? list[0]?.img.map((v) => ({ url: v.url }))
                            : [];
                        this.value1 = list[1]?.text ?? "";
                        this.fileList1 = list[1]?.img
                            ? list[1]?.img.map((v) => ({ url: v.url }))
                            : [];
                        this.value2 = list[2]?.text ?? "";
                        this.fileList2 = list[2]?.img
                            ? list[2]?.img.map((v) => ({ url: v.url }))
                            : [];
                    }
                });
            }
        }
        // 代运营身份 发布
        if (options.releaseManId) this.releaseManId = options.releaseManId;
        if (options.currentTab) this.currentTab = options.currentTab;
    },
    methods: {
        // 标签
        openList(tag) {
            this.$u.route({
                url: "/pages_consultation/counsellings/index",
                params: {
                    styleFirstNum: 2,
                    tag,
                },
            });
        },
        addTalkBtn() {
            console.log("object :>> 111", this.huaTi);
            this.huaTi && (this.huaTi = this.huaTi + " #");
            if (!this.huaTi) this.huaTi = "#";

            console.log("object :>> 222", this.huaTi);
        },
        async publish() {
            if (!this.videoIntro && !this.myStyle)
                return uni.$u.toast("请输入标题");
            if (!this.value && !this.fileList.length)
                return uni.$u.toast("请输入第一组图文");
            const listData = [];
            if (this.value || this.fileList.length)
                listData.push({
                    text: this.value,
                    img: this.fileList,
                    id: 1,
                });
            if (this.value1 || this.fileList1.length)
                listData.push({
                    text: this.value1,
                    img: this.fileList1,
                    id: 2,
                });
            if (this.value2 || this.fileList2.length)
                listData.push({
                    text: this.value2,
                    img: this.fileList2,
                    id: 3,
                });
            this.dataList = listData;
            if (this.myStyle) {
                const myStyleData = JSON.stringify(this.dataList);
                await updateCustomerByCustomerId({
                    myStyle: myStyleData,
                    unionId: this.customerId,
                });
                uni.$u.toast("成功");
                uni.$emit("currentTab", 0);
                uni.navigateBack({
                    delta: 1,
                });
            } else {
                const params = {
                    checkStatus: 0, //审核状态（0:通过 1:不通过）
                    recordType: 1, //记录类型 （0:视频 1:资讯）
                    releaseStatus: 1, //发布状态 （0:未发布 1:发布）
                    infoDetail: JSON.stringify(this.dataList),
                    videoCover: this.fileList[0]?.url ?? "",
                    videoIntro: this.videoIntro,
                };
                if (this.huaTi) params.tag = this.huaTi.replace(/#/g, ",");
                // <!-- T00D 垃圾后端 一套代码写2遍 恶心  代运营走 客户的发布编辑接口 自己业务员走业务员发布编辑-->
                if (this.releaseManId) params.releaseManId = this.releaseManId;
                const { data, code } = !this.type
                    ? this.releaseManId
                        ? await uploadBlogCustomer(params)
                        : await uploadBlog(params)
                    : this.releaseManId
                    ? await editBlogCustomer({
                          ...params,
                          id: this.ids,
                      })
                    : await editBlog({
                          ...params,
                          id: this.ids,
                      });
                if (code === 200) {
                    uni.$u.toast("成功");
                    // 代运营进入 返回主页就是0 坐标 自己发布进入返回就是1坐标
                    // uni.$emit("currentTab", this.releaseManId ? 0 : 1);
                    uni.$emit(
                        "currentTab",
                        this.releaseManId ? this.currentTab : 1
                    );
                    uni.navigateBack({
                        delta: 1,
                    });
                }
            }
        },
        look() {
            const listData = [];
            if (!this.videoIntro && !this.myStyle)
                return uni.$u.toast("请输入标题");
            if (!this.value && !this.fileList.length)
                return uni.$u.toast("请输入第一组图文");
            if (this.value || this.fileList.length)
                listData.push({
                    text: this.value,
                    img: this.fileList,
                    id: 1,
                });
            if (this.value1 || this.fileList1.length)
                listData.push({
                    text: this.value1,
                    img: this.fileList1,
                    id: 2,
                });
            if (this.value2 || this.fileList2.length)
                listData.push({
                    text: this.value2,
                    img: this.fileList2,
                    id: 3,
                });
            this.dataList = listData;
            this.show = true;
        },
        async afterRead(event) {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList.length;
            lists.map((item) => {
                this.fileList.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = this.fileList[fileListLen];
                this.fileList.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        deletePic(event) {
            this.fileList.splice(event.index, 1);
        },
        async afterRead1(event) {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList1.length;
            lists.map((item) => {
                this.fileList1.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = this.fileList1[fileListLen];
                this.fileList1.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        deletePic1(event) {
            this.fileList1.splice(event.index, 1);
        },
        async afterRead2(event) {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList2.length;
            lists.map((item) => {
                this.fileList2.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = this.fileList2[fileListLen];
                this.fileList2.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        deletePic2(event) {
            this.fileList2.splice(event.index, 1);
        },
        async uploadFilePromise(url) {
            const that = this;
            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: `${baseUrl}/${this.$store.getters?.authority}/fileOss/uploadFileImg`,
                    filePath: url,
                    header: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}` || "",
                    },
                    name: "file",
                    success: (res) => {
                        const result = JSON.parse(res.data);
                        if (result.code === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.container {
    background-color: #f6f9ff;
    height: 100%;
    padding: 38rpx 36rpx;
    box-sizing: border-box;
    font-weight: 400;
    color: #588bf3;
    font-size: 28rpx;

    .right {
        width: 144rpx;
        height: 60rpx;
        background: #588bf3;
        border-radius: 400rpx 400rpx 400rpx 400rpx;
        color: #ffffff;
        line-height: 60rpx;
        font-size: 32rpx;
        text-align: center;
    }

    .content {
        background: #ffffff;
        border-radius: 24rpx 24rpx 24rpx 24rpx;
        margin: 40rpx 0;
    }
}

.wrap {
    padding: 30rpx;
    height: calc(100vh - 88rpx);
    overflow-y: scroll; // 超出滚动
    overscroll-behavior: none; // 禁止滚动溢出
}

.talkBox {
    width: 112rpx;
    height: 40rpx;
    background: #588bf3;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    line-height: 40rpx;
    text-align: center;
    color: #fff;
    font-weight: 400;
    font-size: 28rpx;
    margin: 0 0 16rpx 60rpx;
}
.huaTiBox {
    ::v-deep .u-textarea__field {
        color: #588bf3 !important;
    }
}
</style>
